<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            /* text-align: center; */
            
        }
        .box {
            
            margin:0 auto;
            display: table;

        }
    </style>
</head>
<body>
    <select name="" id="memorySelect">
        <option value="">请选择</option>
        <option value="32G">32G</option>
        <option value="16G">16G</option>
    </select>

    <select name="" id="colorSelect">
        <option value="">请选择</option>
        <option value="red">红色</option>
        <option value="blue">蓝色</option>
    </select>

    <br>
    数量：<input type="text" id="numberInput"> 
        
    <br>
    颜色是：<div id="colorInfo"></div>
    数量是：<div id="numberInfo"></div>
    <button id="nextBtn" disabled="true">加入购物车</button>

    <script>
        var colorSelect = document.getElementById('colorSelect'),
            numberInput = document.getElementById('numberInput'),
            colorInfo = document.getElementById('colorInfo'),
            numberInfo = document.getElementById('numberInfo'),
            nextBtn = document.getElementById('nextBtn');
            
        var goods = {
            red:3,
            blue:6
        }

        colorSelect.onchange = function() {

            var color = this.value; // this 指向当前change事件
            var number = parseInt(numberInput.value);
            var stock = goods[color];
           
            colorInfo.innerHTML = color;

            checkout(color,number,stock);
            
        }


        numberInput.oninput = function() {

           console.log('oninput');
            var number = parseInt(this.value);
            numberInfo.innerHTML = number;
            var color = colorSelect.value;
            var stock = goods[color];

            checkout(color,number,stock);
            
        }

        nextBtn.onclick = function() {
            window.alert('加入购物车成功'+ colorSelect.value + ":" + numberInput.value);
        }

        function checkout(color,number,stock) {
            if(!color) {
                nextBtn.disabled = true;
                nextBtn.innerHTML = '请输入正确的手机颜色';
                return;
            }

            if(!number || number <= 0) {
                nextBtn.disabled = true;
                nextBtn.innerHTML = '请输入正确的购买数量';
                return;
            }


            if(number > stock) {
                
                nextBtn.disabled = true;
                nextBtn.innerHTML = '库存不足';
                return;
            }

            nextBtn.disabled = false;
            
            nextBtn.innerHTML = '加入购物车';
        }

        // var goods = {
        //     'red|32G':3,
        //     'red|16G':0,
        //     'blue|32G':6,
        //     'blue|16G':2
        // }


    </script>
</body>
</html>